package com.demo.jdk.lambda;

import com.demo.model.Address;
import com.demo.model.User;
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class LambdaList {

    /**
     * lambda表达式处理嵌套for循环
     * @return
     */
    public List<String> doubleForeach() {
        List<User> list = new ArrayList<>();
        for (long i = 0; i < 2; i++) {
            Address address = new Address();
            address.setUserAddress(i + "");

            User user = new User();
            user.setUserId(i);
            user.setAddressList(Lists.newArrayList(address));

            list.add(user);
        }

        return list.stream()
                .map(User::getAddressList)
                .flatMap(Collection::stream)
                .map(Address::getUserAddress)
                .collect(Collectors.toList());
    }

    /**
     * lambda表达式处理嵌套for循环，简化版本
     * @return
     */
    public List<String> doubleForeach1() {
        List<User> list = new ArrayList<>();
        for (long i = 0; i < 2; i++) {
            Address address = new Address();
            address.setUserAddress(i + "");

            User user = new User();
            user.setUserId(i);
            user.setAddressList(Lists.newArrayList(address));

            list.add(user);
        }

        return list.stream()
                .flatMap((User user) -> Stream.of(user.getAddressList().toArray(new Address[]{})))
                .map(Address::getUserAddress)
                .collect(Collectors.toList());
    }
}
